<?php
/**
 * 处理问题搜索的模块
 */
if (!defined('ABSPATH')) {
	define('ABSPATH', dirname(dirname(__FILE__)) . '/');
}

require_once ABSPATH . 'dr-config.php';
require_once ABSPATH . DRINC . '/dr-base.php';
require_once ABSPATH . DRINC . '/dr-functions.php';
require_once ABSPATH . DRINC . '/dr-themes.php';

require_once ABSPATH . DRINC . '/dr-smarty.php';
require_once ABSPATH . DRINC . '/mygravatar.php';
require_once ABSPATH . DRINC . '/vendors/sphinx/sphinxapi.php';


$questions_per_page = 20;

$us_query = isset($_GET['query']) ? trim($_GET['query']) : '';
$us_page  = isset($_GET['page']) ? intval($_GET['page']) : 0;

if ($us_page != 0) {
	$page = $us_page;
} else {
	$page = 1;
}

$offset = ($page - 1) * $questions_per_page;
$limits = $questions_per_page;
$query = $us_query;

$sphinx = new SphinxClient();
$sphinx->SetServer('localhost', 9312);
$sphinx->SetArrayResult(true);
$sphinx->SetLimits($offset, $limits);
$results = $sphinx->Query($query, '*');

// 初始化将要返回的数据
$content = array();
$content['search_results'] = $results;

if (isset($results['matches'])) {
	// 获得搜索获取的问题的ID
	$match_ids = array();
	foreach ($results['matches'] as $match) {
		$match_ids[] = $match['id'];
	}
	$question_ids = implode(',', $match_ids);
	$content['questions'] = get_searched_questions_with_ids($question_ids);
    
	foreach ($content['questions'] as &$question) {
		$question['content'] = strip_tags($question['content']);
		$question['user_avatar'] = (string) new MyGravatar($question['user_email'], 32);
	}
}



$smarty->assign('page_title', get_search_page_title($query));

$content['top_navs'] = get_page_top_navigation();
$content['menus'] = get_page_menus('');
$content['tabs'] = get_page_tabs('search', '');

$smarty->assign('content', $content);

$smarty->display('search.tpl');

/* ====搜索相关的函数==== */

/**
 * 获得搜索页面的标题
 *
 * @param  $query
 * @return string
 */
function get_search_page_title($query) {
	$page_title = "搜索 - ";
	if (! empty($query)) {
		$page_title .= $query . ' - ' . get_site_name();
	} else {
		$page_title .= 'null - ' . get_site_name();
	}
	return $page_title;
}

function get_searched_questions_with_ids($question_ids) {
	$posts = array(
		'action' => 'get_searched_questions_with_ids',
		'ids'    => $question_ids,
	);

	return json_decode(dr_server_request('dr-app-questions.php', $posts), true);
}

